package mulis.photoviewer;

import dvsdk.GlobalConfig;
import dvsdk.form.JImageFileChooser;
import dvsdk.util.Lang;
import dvsdk.util.Util;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Ivan
 */
public class DViewer extends javax.swing.JDialog {

    public static int thumbnailWidth = GlobalConfig.THUMBINAL_WIDTH;
    public static int thumbnailHeight = GlobalConfig.THUMBINAL_HEIGHT;
    public int modalResult = 0;
    
    /** Creates new form DViewer */
    public DViewer(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        Util.maxiSizer(this);      
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        imgBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(DViewer.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setMinimumSize(new java.awt.Dimension(750, 550));
        setName("Form"); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        jSeparator1.setName("jSeparator1"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 692, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 184, Short.MAX_VALUE)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton4)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        imgBtn.setText(resourceMap.getString("imgBtn.text")); // NOI18N
        imgBtn.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        imgBtn.setBorderPainted(false);
        imgBtn.setContentAreaFilled(false);
        imgBtn.setDefaultCapable(false);
        imgBtn.setDoubleBuffered(true);
        imgBtn.setFocusPainted(false);
        imgBtn.setMinimumSize(new java.awt.Dimension(600, 400));
        imgBtn.setName("imgBtn"); // NOI18N
        imgBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jScrollPane1.setViewportView(imgBtn);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents


   
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        JImageFileChooser chooser = new JImageFileChooser(JImageFileChooser.lastFilePath);
        if (chooser.showOpenDialog(this)==JImageFileChooser.APPROVE_OPTION) {
            JImageFileChooser.lastFilePath = chooser.getSelectedFile().getPath();
            try {
                imgBtn.setIcon(new ImageIcon(Util.resizeImage(ImageIO.read(chooser.getSelectedFile()), thumbnailWidth, thumbnailHeight)));
                jButton2.setEnabled(true);
                jButton3.setEnabled(true);
                imgBtn.setText("");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Не могу обработать изображение, ошибка: "+
                        ex.getLocalizedMessage(), "Ошибка обработки", JOptionPane.ERROR_MESSAGE);
                return;
            }
            //ImgBtn.setIcon(new javax.swing.ImageIcon(chooser.getSelectedFile().toString()));
            //ImgBtn.setIcon(Toolkit.getDefaultToolkit().getImage(chooser.getSelectedFile()));
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * Диалог выбора нового изображения
     */
    public BufferedImage execute() {
        if (imgBtn==null) {
            jButton2.setEnabled(false);
            jButton3.setEnabled(false);
            setTitle("Добавить изображение...");
            
        } else {
            setTitle("Изменить изображение...");
            imgBtn.setText("");
        }
        setVisible(true);
        if (imgBtn.getIcon()==null)
            return null;
        BufferedImage img = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
        img.getGraphics().drawImage(((ImageIcon)(imgBtn.getIcon())).getImage(), 0, 0, this);
        return img;
    }
    /**
     * Диалог просмотра существующего изображения
     * @param src
     * @return 
     */
    public BufferedImage execute(BufferedImage src) {
        imgBtn.setIcon(new ImageIcon(Util.resizeImage(src, thumbnailWidth, thumbnailHeight)));
        return execute();
    }
    
  
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        modalResult = 1;
        //setVisible(false);
        dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        if (imgBtn.getIcon()==null) {
           JOptionPane.showMessageDialog(this, "Сначала загрузите изображение.", 
                   "Пусто", JOptionPane.WARNING_MESSAGE);
           return;
        }
            
        try {
            JFileChooser jfc = new JFileChooser();
            jfc.setAcceptAllFileFilterUsed(false);
            jfc.addChoosableFileFilter(Util.createFileFilter("jpg", false, "jpg"));
            jfc.addChoosableFileFilter(Util.createFileFilter("gif", false, "gif"));
            jfc.addChoosableFileFilter(Util.createFileFilter("png", false, "png"));

            if (Lang.setUpdateUI(jfc).showSaveDialog(this)==JFileChooser.APPROVE_OPTION) {
                String fileName = jfc.getSelectedFile().toString();
                FileFilter filter = jfc.getFileFilter();
                if (!fileName.endsWith("."+filter.getDescription()))
                    fileName+="."+filter.getDescription();
                File file = new File(fileName);
                if (file.exists())
                    if (JOptionPane.showConfirmDialog(this, "Файл с таким именем уже существует, перезаписать?", 
                            "Подтвердите", JOptionPane.YES_NO_CANCEL_OPTION, 
                            JOptionPane.QUESTION_MESSAGE)!=JOptionPane.YES_OPTION)
                        return;
                BufferedImage img = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);

                img.getGraphics().drawImage(((ImageIcon)(imgBtn.getIcon())).getImage(), 0, 0, this);            
                ImageIO.write(img, filter.getDescription(), file);
                img=null; file=null; fileName=null;
                this.dispose();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Не могу сохранить изображение, ошибка: "+
                    e.getLocalizedMessage(), "Ошибка", JOptionPane.ERROR_MESSAGE);
            this.dispose();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(this, "Удалить изображение?", "Подтвердите", 
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)==JOptionPane.YES_OPTION) {
            modalResult = 0;
            imgBtn.setIcon(null);
            //setVisible(false);
            dispose();
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                DViewer dialog = new DViewer(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton imgBtn;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables
}
